package com.aiju.cash.ui.account;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.cash.R;
import com.aiju.cash.core.api.AccountApi;
import com.aiju.cash.ui.account.adapter.AccountInfoAdapter;
import com.aiju.cash.ui.account.adapter.CalenderAdatper;
import com.aiju.cash.ui.account.entity.ItemList;
import com.aiju.cash.util.GsonHelper;
import com.aiju.utils.DateUtil;
import com.aiju.utils.PriceUtil;
import com.aiju.utils.Util;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.loadmore.SwipeRefreshHelper;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.prolificinteractive.materialcalendarview.format.TitleFormatter;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @author: 佐为
 * @date: 2017-03-31 09:45
 * @version: V1.0
 * @Description: 日期下的账目
 */
public class AccountCalendarActivity extends BaseTitleActivity implements SwipeRefreshHelper.OnSwipeRefreshListener, OnLoadMoreListener {

    private String acccountId;
    private Calendar calendar;
    private MaterialCalendarView calendarView;
    private int pageSize = 10;
    private int currentNum = 1;

    private TextView direction, timeTextView;

    private RecyclerView recyclerView;
    private SwipeRefreshLayout mSryt;
    private SwipeRefreshHelper mSwipeRefreshHelper;
    private RecyclerAdapterWithHF mAdapter;
    private boolean isLoad;
    private boolean isRefresh;

    private View view;
    private CalenderAdatper adatper;

    private List<ItemList.Item> items = new ArrayList<>();
    private String stringByFormat;

    private TextView outTextView, inTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_calendar);
        setCenterTitle("选择日期");
        setRightTitle("今日账本");
        acccountId = getIntent().getStringExtra("accountId");
        calendar = Calendar.getInstance();
        stringByFormat = DateUtil.getCurrentDate(DateUtil.dateFormatYMD);
        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //回到今天
                calendarView.setCurrentDate(calendar.getTime());
                calendarView.setSelectedDate(calendar.getTime());

                stringByFormat = DateUtil.getCurrentDate(DateUtil.dateFormatYMD);
                items.clear();
                requsetListByDate();
            }
        });

        view = findViewById(R.id.iv_empty);
        mSryt = (SwipeRefreshLayout) this.findViewById(R.id.sryt_swipe_listview);
        mSryt.setColorSchemeColors(getResources().getColor(R.color.app_title_color));

        recyclerView = (RecyclerView) findViewById(R.id.lv_account_calender);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adatper = new CalenderAdatper(items);
        adatper.setOnItemClickListener(new AccountInfoAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(ItemList.Item item) {
                Intent intent = new Intent(AccountCalendarActivity.this, AccountItemInfoActivity.class);
                intent.putExtra("item", item);
                startActivity(intent);
            }
        });
        mAdapter = new RecyclerAdapterWithHF(adatper);
        recyclerView.setAdapter(mAdapter);

        mSwipeRefreshHelper = new SwipeRefreshHelper(mSryt);
        mSwipeRefreshHelper.setOnSwipeRefreshListener(this);
        mSwipeRefreshHelper.setOnLoadMoreListener(this);

        timeTextView = (TextView) findViewById(R.id.tv_budget_time);
        direction = (TextView) findViewById(R.id.iv_calender_direction);

        inTextView = (TextView) findViewById(R.id.tv_budget_money_in);
        outTextView = (TextView) findViewById(R.id.tv_budget_money_out);
        direction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (calendarView.getVisibility() == View.VISIBLE) {
                    calendarView.setVisibility(View.GONE);
                    direction.setText("展开");
                    setDrawable(direction, R.mipmap.ic_calendar_down);
                } else {
                    calendarView.setVisibility(View.VISIBLE);
                    direction.setText("收起");
                    setDrawable(direction, R.mipmap.ic_calendar_up);
                }
            }
        });
        calendarView = (MaterialCalendarView) findViewById(R.id.calendarView);
        calendarView.setSelectedDate(calendar.getTime());//默认选中
        calendarView.setTitleFormatter(new TitleFormatter() {
            @Override
            public CharSequence format(CalendarDay day) {
                return DateUtil.getStringByFormat(day.getDate(), DateUtil.dateFormatYM_C);
            }
        });
        calendarView.setOnDateChangedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
                items.clear();
                stringByFormat = DateUtil.getStringByFormat(date.getDate(), DateUtil.dateFormatYMD);
                requsetListByDate();
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        requsetListByDate();
    }

    /**
     * 根据日期请求账目
     */
    private void requsetListByDate() {
        new AccountApi(mDialogHelper).listByDate(acccountId, stringByFormat, String.valueOf(currentNum),
                String.valueOf(pageSize), new SimpleHttpCallback() {
                    @Override
                    protected void onDataSuccess(String data) {
                        String item = "";
                        String sum = "";
                        try {
                            JSONObject jsonObject = new JSONObject(data);
                            sum = jsonObject.getJSONArray("sum").toString();
                            item = jsonObject.getJSONArray("list").toString();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        List<ItemList.Item> list = GsonHelper.convertEntities(item, ItemList.Item.class);
                        if (!Util.isEmpty(list)) {
                            if (isRefresh) {
                                items.clear();
                            }
                            items.addAll(list);
                        }
                        adatper.notifyDataSetChanged();
                        completeView(list);

                        timeTextView.setText(stringByFormat);

                        List<ItemList.Sum> sums = GsonHelper.convertEntities(sum, ItemList.Sum.class);
                        if (!Util.isEmpty(sums)) {
                            for (ItemList.Sum d : sums) {
                                if (d.getType() == 1) {
                                    inTextView.setText("收 " + PriceUtil.formatDouble(d.getMoney()));
                                }
                                if (d.getType() == 2) {
                                    outTextView.setText("支 " + PriceUtil.formatDouble(d.getMoney()));
                                }
                            }
                        } else {
                            inTextView.setText("收 " + PriceUtil.formatDouble(0d));
                            outTextView.setText("支 " + PriceUtil.formatDouble(0d));
                        }
                    }
                });
    }

    /**
     * 设置底部
     *
     * @param textView
     * @param id
     */
    private void setDrawable(TextView textView, int id) {
        Drawable drawable = getResources().getDrawable(id);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        textView.setCompoundDrawables(null, null, null, drawable);
    }


    @Override
    public void loadMore() {
        isLoad = true;
        currentNum += 1;
        requsetListByDate();
    }

    @Override
    public void onfresh() {
        isRefresh = true;
        currentNum = 1;
        requsetListByDate();
    }

    /**
     * 加载完成视图动作
     *
     * @param blotterLists
     */
    private void completeView(List<ItemList.Item> blotterLists) {
        //加载
        if (isLoad) {
            isLoad = false;
            mSwipeRefreshHelper.loadMoreComplete(true);
        }
        //刷新
        if (isRefresh) {
            isRefresh = false;
            mSwipeRefreshHelper.refreshComplete();
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }

        if (blotterLists.size() < pageSize) {
            mSwipeRefreshHelper.setLoadMoreEnable(false);
        } else {
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }
        checkIfEmpty();
    }

    private void checkIfEmpty() {
        if (adatper != null && mSwipeRefreshHelper != null) {
            final boolean emptyViewVisible = adatper.isEmpty();
            if (emptyViewVisible) {
                view.setVisibility(View.VISIBLE);
            } else {
                view.setVisibility(View.GONE);
            }
        }
    }
}
